package com.shukesmart.speech.ui.note;

import static android.Manifest.permission.BLUETOOTH;
import static android.Manifest.permission.BLUETOOTH_ADMIN;
import static android.Manifest.permission.MANAGE_EXTERNAL_STORAGE;
import static android.Manifest.permission.MODIFY_AUDIO_SETTINGS;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.AudioFormat;
import android.media.AudioTrack;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.shukesmart.skspeech.SKSpeechListener;
import com.shukesmart.skspeech.SKSpeechRecognize;
import com.shukesmart.speech.R;
import com.shukesmart.speech.databinding.FragmentHomeBinding;
import com.shukesmart.speech.databinding.FragmentNoteBinding;
import com.shukesmart.speech.db.NoteAdapter;
import com.shukesmart.speech.db.NoteBean;
import com.shukesmart.speech.db.NoteDao;
import com.shukesmart.speech.utils.AudioPlayer;
import com.shukesmart.speech.utils.microPhoneRecorder;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class NoteFragment extends Fragment {
    private static final String TAG = "NoteFragment";
    private FragmentNoteBinding binding;
    private List<NoteBean> devices;
    Button start_note_record;
    Button stop_note_record;
    Button save_note;
    EditText multiLineEditText;
    ListView listView;
    private volatile boolean isRunning = false;
    private InputStream is = null;
    SKSpeechRecognize skSpeechRecognize;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        NoteViewModel dashboardViewModel =
                new ViewModelProvider(this).get(NoteViewModel.class);

        binding = FragmentNoteBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        save_note = binding.saveNote;
        multiLineEditText = binding.multiLineEditText;
         listView = binding.listview;
        start_note_record = binding.startNoteRecord;

        initSpeechRecognizer();

        start_note_record.setOnClickListener(v -> {

            // 麦克风
            if (!isRunning) {
                isRunning = true;
                start_note_record.setVisibility(View.INVISIBLE);
                stop_note_record.setVisibility(View.VISIBLE);
                listView.setVisibility(View.INVISIBLE);
                multiLineEditText.setVisibility(View.VISIBLE);
                try {
                    CreateSLL();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(requireActivity(), "正在录音中，请稍后再试", Toast.LENGTH_SHORT).show();
            }
        });

        stop_note_record = binding.stopNoteRecord;

        stop_note_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start_note_record.setVisibility(Button.INVISIBLE);
                stop_note_record.setVisibility(ImageView.INVISIBLE);
                try {
                    if (is != null) {
                        is.close();
                        is = null;
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        save_note.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                renameDialog();
            }
        });

        NoteDao noteDao = new NoteDao(requireActivity());


        devices = noteDao.getList(1);

        NoteAdapter arrayAdapter = new NoteAdapter(requireActivity(),
                R.layout.note_list_item, devices);
        listView.setAdapter(arrayAdapter);


        return root;
    }

    String asrResult = "";
    //创建目录
    final Handler cwjHandler = new Handler();

    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            stop_note_record.setVisibility(Button.INVISIBLE);
            start_note_record.setVisibility(ImageView.VISIBLE);
            save_note.setVisibility(Button.VISIBLE);
        }
    };

    private void initSpeechRecognizer() {
        Handler handler = new Handler(Looper.getMainLooper());

        SKSpeechRecognize.setPrintLog(true);
        //初始化
        try {

            skSpeechRecognize = SKSpeechRecognize.createRecognizer(requireActivity(), "bb7b4c5122f011ef8acfedca1adaee2b", "c637dwfee475dsfwb09de4", "shukesmart");
            skSpeechRecognize.setSkSpeechListener(new SKSpeechListener() {
                @Override
                public void onInit(boolean isSuccess, String msg) {
                }

                @Override
                public void onBegin() {
                    Log.i(TAG, "onBegin: ");

                }

                @Override
                public void onCompleted(int code) throws IOException {
                    Log.i(TAG, "onCompleted: " + code);

                    isRunning = false;
                    cwjHandler.post(mUpdateResults); //高速UI线程可以更新结果了
                }

                @Override
                public void onError(String msg) {

                }

                @Override
                public void onAsrResult(boolean isFinal, String result) {


                    handler.post(new Runnable() {
                        @Override
                        public void run() {


                            if (isFinal) {

                                asrResult += result;
                                multiLineEditText.setText(asrResult);
                            } else {
                                multiLineEditText.setText(asrResult + result);
                            }
                        }
                    });


                }

                @Override
                public void onTraslateResult(boolean b, String s) {

                }

                @Override
                public void onTTSResult(byte[] bytes) throws IOException {

                }

                @Override
                public void onAsrEnd(String allResult) {
                    Log.i(TAG, "onAsrEnd: " + allResult);
                }

                @Override
                public void onTraslateEnd(String allResult) {
                    Log.i(TAG, "onTraslateEnd: " + allResult);
                }

                @Override
                public void onTTSEnd(byte[] result) {
                    Log.i(TAG, "onTTSEnd: " + Arrays.toString(result));
                }

                @Override
                public void onFlushChunk() {
                }
            });



            boolean set_ret = skSpeechRecognize.setParameter(3, 119, 26, 16000, 1, AudioFormat.ENCODING_PCM_16BIT, "", true);

            if (!set_ret) {
                System.out.println("设置参数失败");

            }

        } catch (ExecutionException | InterruptedException | IOException |
                 UnrecoverableKeyException | CertificateException | KeyStoreException |
                 NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }

    void CreateSLL() throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //实例化录音对象
                is = microPhoneRecorder.getInstance(requireActivity());

                int sendSize = 16000;

                byte[] audio_bin = new byte[sendSize];
                int readSize;
                do {
                    try {
                        readSize = is.read(audio_bin, 0, sendSize);
                    } catch (IOException | RuntimeException e) {

                        readSize = -2;
                        try {
                            skSpeechRecognize.send_audio_end();
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }


                    }
                    if (readSize > 0) {
                        try {
                            skSpeechRecognize.send_audio(audio_bin);
                        } catch (IOException | UnrecoverableKeyException | CertificateException |
                                 KeyStoreException | NoSuchAlgorithmException |
                                 KeyManagementException e) {
                            throw new RuntimeException(e);
                        }
                    }

                } while (readSize > 0);


            }
        }).start();


    }

    private void renameDialog() {
        final EditText et = new EditText(requireActivity());
        new AlertDialog.Builder(requireActivity()).setMessage("重命名")//setTitle()
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            Toast.makeText(requireActivity(), "名称不能为空！" + input, Toast.LENGTH_LONG).show();
                        } else {
                            NoteDao noteDao = new NoteDao(requireActivity());
                            NoteBean noteBean = new NoteBean();
                            noteBean.setContext(multiLineEditText.getText().toString());
                            noteBean.setTitle(input);

                            noteDao.insert(noteBean);

                            multiLineEditText.setText("");
                            save_note.setVisibility(View.INVISIBLE);
                            multiLineEditText.setVisibility(View.INVISIBLE);
                            listView.setVisibility(View.VISIBLE);
                            start_note_record.setVisibility(View.VISIBLE);
                            stop_note_record.setVisibility(View.INVISIBLE);
                            devices = noteDao.getList(1);
                            NoteAdapter arrayAdapter = new NoteAdapter(requireActivity(),
                                    R.layout.note_list_item, devices);
                            listView.setAdapter(arrayAdapter);
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override

    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    skSpeechRecognize.stopRealTimeRecorder();
                    skSpeechRecognize.closeSpeech();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}